<template>
  <el-dialog
    :model-value="visible"
    width="680px"
    title="发送钥匙"
    @close="handleClose"
    :fullscreen="mobile"
    :destroy-on-close="true"
  >
    <el-form :model="form" label-width="140px" ref="formRef" :rules="rules">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="接收者账号" prop="account">
        <el-input v-model="form.account" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="类型" prop="keyType">
        <el-radio-group v-model="form.keyType" @change="handleTypeChange">
          <el-radio :label="1">限时</el-radio>
          <el-radio :label="2">永久</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="远程开锁" prop="remoteEnable">
        <el-switch v-model="form.remoteEnable"></el-switch>
      </el-form-item>
      <el-form-item label="有效期" prop="date" v-if="form.keyType === 1">
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD HH:mm:ss"
          @change="handleDateChange"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleOk" :loading="loading">确定</el-button>
    </template>
  </el-dialog>
</template>
<script setup name="sendKeyDl">
import useAppStore from '@/store/modules/app'
import { getCurrentInstance, watch } from 'vue'
import LockApi from "@/api/device/lock.js";

const { proxy } = getCurrentInstance()

const emit = defineEmits(['ok', 'cancel'])
const props = defineProps({
  visible: Boolean,
  lockId: String
})

const loading = ref(false)
const dateRange = ref([])
const mobile = computed(() => useAppStore().device === 'mobile')

const form = reactive({
  name: '',
    account: '',
    keyType: 1,
    startDate: '',
    endDate: '',
    remoteEnable: true
})

const rules = reactive({
  name: [{ required: true, message: '请输入接收人姓名', trigger: 'blur'}],
  account: [{ required: true, message: '请输入手机号', trigger: 'blur'}, { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur'}],
  startDate: [{ required: true, message: '请选择有效期', trigger: 'change'}],
  endDate: [{ required: true, message: '请选择有效期', trigger: 'change'}]
})

// 监听对话框显示状态
watch(() => props.visible, (val) => {
  if (val) {
    // 对话框打开时初始化表单
    initForm()
  }
})

// 初始化表单
function initForm() {
  // 重置表单字段
  form.name = ''
  form.account = ''
  form.keyType = 1
  form.remoteEnable = true
  
  // 设置默认时间范围
  setDefaultTimeRange()
}

// 设置默认时间范围
function setDefaultTimeRange() {
  const now = new Date()
  const twoHoursLater = new Date(now.getTime() + 2 * 60 * 60 * 1000) // 当前时间加2小时
  
  // 格式化时间
  const formatDate = (date) => {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
  
  form.startDate = formatDate(now)
  form.endDate = formatDate(twoHoursLater)
  
  // 更新日期选择器的值
  dateRange.value = [form.startDate, form.endDate]
}

function handleClose() {
  emit('cancel')
}

function handleOk() {
  proxy.$refs['formRef'].validate(valid => {
    if (valid) {
      // 验证限时类型时必须有时间范围
      if (form.keyType === 1 && (!form.startDate || !form.endDate)) {
        proxy.$message.error('请选择有效期')
        return
      }
      
      loading.value = true

      console.log(form)
      
      // 只提取需要的表单字段，而不是整个响应式对象
      const params = {
        lockId: props.lockId,
        name: form.name,
        account: form.account,
        keyType: form.keyType,
        startDate: form.startDate,
        endDate: form.endDate,
        remoteEnable: form.remoteEnable ? 1 : 2
      }
      
      LockApi.sendKey(params).then(res => {
        if (res.code === 200) {
          proxy.$modal.msgSuccess('发送钥匙成功')
          emit('ok', params)
        } else {
          proxy.$modal.msgError(res.msg || '发送钥匙失败')
        }
      }).catch(err => {
        console.error(err)
        proxy.$modal.msgError('发送钥匙失败')
      }).finally(() => {
        loading.value = false
      })
    }
  })
}

function handleTypeChange(value) {
  if (value === 2) {
    // 永久类型
    form.startDate = new Date().toISOString().slice(0, 19).replace('T', ' ')
    form.endDate = '2099-12-31 00:00:00'
    dateRange.value = [form.startDate, form.endDate]
  } else {
    // 限时类型，设置默认时间范围
    setDefaultTimeRange()
  }
}

function handleDateChange(val) {
  if (val) {
    form.startDate = val[0]
    form.endDate = val[1]
  } else {
    form.startDate = ''
    form.endDate = ''
  }
}

// 初始化
initForm()
</script>
